package com.ksd1.notes;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.LinearLayout;

import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.ksd1.notes.db.NoteDB;
import com.ksd1.notes.util.NoteDirHelper;
import com.google.android.material.floatingactionbutton.FloatingActionButton;


import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import com.google.android.material.navigation.NavigationView;
import com.ksd1.notes.util.TimeTool;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    //    控制
    private boolean isNote = true;//控制初始时显示
    public static boolean sfinish = false;//是否展示以完成列表
    public static List<NoteDB.Todo> allList;//所有的todoList未完成的以及完成的

    public static volatile int cnt;//最后一个待完成
    private int mSelectedPosition;
    public static final int NOTE_ADD = 1;
    public static final int NOTE_EDIT = 2;
    public static long currentType = 0;//目前的分类/代表全部

    //    控件
    private SearchView mSearchView;//搜索框
    private TextView todo;//上方菜单
    private TextView note;
    private LinearLayout noteLayout, todoLayout;
    private FloatingActionButton fab;//悬浮按钮
    private DrawerLayout mDrawerLayout;//滑动菜单
    private NavigationView navigationView;//滑动菜单的内容

    //note
    public static RecyclerView note_recyclerView;
    public static List<NoteDB.Note> noteList;
    public static NoteAdapter noteAdapteradapter;

    //todo
    public static RecyclerView todo_recyclerView;
    public static List<NoteDB.Todo> todoList;//渲染的列表
    private List<NoteDB.Todo> todoList_save;//保存原列表
    public static TodoAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        super.onCreate(savedInstanceState);
    }

    /**
     * 初始化变量
     */
    @Override
    protected void initVariables() {
        NoteDB.getInstance().open(this);//初始化数据库

        note_recyclerView = findViewById(R.id.todo_recyclerView);

        todo = findViewById(R.id.toolbar_todo);
        note = findViewById(R.id.toolbar_note);
        noteLayout = findViewById(R.id.note_layout);
        todoLayout = findViewById(R.id.todo_layout);
        fab = findViewById(R.id.fab);
        mDrawerLayout = findViewById(R.id.mDrawerLayout);
        navigationView = findViewById(R.id.dir_view);
//        mSearchView = findViewById(R.id.searchView);
        sfinish = false;//暂时写死，以后在xml文件定义全局变量

        initData();
        initNoteList();//note列表
        initTodoList();//todolist列表

        //设置菜单
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.dir);
        }

    }

    /**
     * 添加监听事件、视图
     */
    @Override
    protected void initViews(Bundle savedInstanceState) {
        todo.setOnClickListener(this);
        note.setOnClickListener(this);
        fab.setOnClickListener(this);

        // 设置搜索文本监听
        /*mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            // 当点击搜索按钮时触发该方法
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            // 当搜索内容改变时触发该方法
            @Override
            public boolean onQueryTextChange(String newText) {
                if (!TextUtils.isEmpty(newText.trim())){
                    searchTags(newText.trim());
                }else{
                    searchTags("");
                }
                return false;
            }
        });
*/
        showNoteList();
        showTodoList();

        initNavView();

        //初始是否展示已完成列表
        if (!sfinish)
            showFinish();

        //初始layout的选取
        if (isNote) {
            noteLayout.setVisibility(View.VISIBLE);
            todoLayout.setVisibility(View.GONE);
        } else {
            todoLayout.setVisibility(View.VISIBLE);
            noteLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 监测用户初次登录
     * 往日记和待办里面添加信息
     */
    protected void initData(){
        if(TimeTool.getInstance().getField("isfirst").equals("1")) return;

        //记事本部分
        StringBuilder sb = new StringBuilder();
        sb.append("帮助文档\n");
        sb.append("# 大标题\n");
        sb.append("## 二级标题\n");
        sb.append("### 三级标题\n");
        sb.append("{居中}\n");
        sb.append("- 列表\n");
        sb.append("**加粗**\n");
        sb.append("> 引用\n\n\n");
        sb.append("项目地址：\nhttps://gitee.com/ksd1/todolist.git\n");
        sb.append("创作不易，欢迎start！\n");
        NoteDB.Note note = new NoteDB.Note("帮助文档", sb.toString(), new Date().getTime());
        note.type = 1;
        NoteDB.getInstance().ninsert(note);

        //todolist部分
        List<NoteDB.Todo> ltodo = new LinkedList<>();
        NoteDB.Todo todo = new NoteDB.Todo("第一条待办", 0);
        NoteDB.Todo todo2 = new NoteDB.Todo("长按可以进行删除", 0);
        NoteDB.Todo todo3 = new NoteDB.Todo("点击右上角可以选择显示已完成列表", 0);
        ltodo.add(todo3);
        ltodo.add(todo2);
        ltodo.add(todo);
        NoteDB.getInstance().insert(ltodo);

        TimeTool.getInstance().setField("isfirst", "1");
    }

    /**
     * 处理滑动窗口中的点击事件
     */
    protected void initNavView(){
        navigationView.setCheckedItem(R.id.dir_all);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch(menuItem.getItemId()){
                    case R.id.dir_all:
                        NoteDirHelper.changeDir("全部");
                        currentType = 0;
                        note.setText("便签");
                        break;
                    case R.id.dir_default:
                        NoteDirHelper.changeDir("未分类");
                        currentType = 1;
                        note.setText("未分类");
                        break;
                    case R.id.dir_study:
                        NoteDirHelper.changeDir("学习");
                        currentType = 2;
                        note.setText("学习");
                        break;
                    case R.id.dir_life:
                        NoteDirHelper.changeDir("生活");
                        currentType = 3;
                        note.setText("生活");
                        break;
                    case R.id.dir_new:
                        NoteDirHelper.addDir(MainActivity.this);
                        break;
                    default:
                        break;

                }



                mDrawerLayout.closeDrawers();
                return true;
            }
        });
    }

    @Override
    protected void loadData() {

    }


    protected void initNoteList() {
        noteList = NoteDB.getInstance().nquery();
    }


    /**
     * 数据库初始化todoList
     */
    protected void initTodoList() {
        todoList = NoteDB.getInstance().query();

        //初始化数量
        cnt = -1;
        int size = todoList.size();
        for (int i = 0; i < size; i++) {
            if (todoList.get(i).status == 0) cnt++;
            else break;
        }
    }

    /**
     * 程序退出时数据库保存todoList
     */
    protected void saveTodoList() {
//        Toast.makeText(this, "数据库保存数据", Toast.LENGTH_SHORT).show();
        if (!sfinish) {
            sfinish = true;
            showFinish();
        }
        NoteDB.getInstance().insert(todoList);
    }


    /**
     * 展示待办列表
     */
    protected void showTodoList() {
        todo_recyclerView = findViewById(R.id.todo_recyclerView);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 1);
        todo_recyclerView.setLayoutManager(layoutManager);
        adapter = new TodoAdapter(todoList);
        todo_recyclerView.setAdapter(adapter);
    }


    protected void showNoteList() {
        note_recyclerView = findViewById(R.id.note_recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        note_recyclerView.setLayoutManager(linearLayoutManager);
        noteAdapteradapter = new NoteAdapter(noteList);
        note_recyclerView.setAdapter(noteAdapteradapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }


    /**
     * @param item 被点击的菜单
     * @return boolean
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home://打开滑动菜单
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.action_show_finish:
            case R.id.action_show_finish_gone:
//                Toast.makeText(this, "显示已完成列表", Toast.LENGTH_SHORT).show();
                sfinish = !sfinish;
                showFinish();
                break;
            case R.id.action_add:
                Toast.makeText(this, "列表模式", Toast.LENGTH_SHORT).show();
                break;
            case R.id.clock_remain://提醒界面
                Intent intent = new Intent(MainActivity.this, RemainClock.class);
                startActivity(intent);
                break;
            default:

        }
        return true;
    }

    /**
     * 显示或隐藏已完成列表
     */
    protected void showFinish() {
        if (!sfinish) {//隐藏已完成列表
            if (allList == null) {
                allList = new LinkedList<>();
            } else {
                allList.clear();
            }

            for (int i = todoList.size() - 1; i > cnt; i--) {
                allList.add(todoList.get(i));
                todoList.remove(i);
                adapter.notifyItemRemoved(i);
            }
        } else {//显示已完成列表
            if (allList == null) return;
            int k = 1;
            for (int i = allList.size() - 1; i >= 0; i--) {
                todoList.add(allList.get(i));
                adapter.notifyItemInserted(cnt + k);
                k++;
            }
        }
    }


    //    改变菜单
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
//        Toast.makeText(this, "初始化菜单被调用", Toast.LENGTH_SHORT).show();
        if (isNote) {//根据标识值判断当前应该启用哪个菜单项
            showDrawerLayout();
            menu.findItem(R.id.action_add).setVisible(true);
            menu.findItem(R.id.action_show_finish).setVisible(false);
            menu.findItem(R.id.action_show_finish_gone).setVisible(false);//菜单

            todoLayout.setVisibility(View.GONE);
            noteLayout.setVisibility(View.VISIBLE);
            todo.setTextColor(getResources().getColor(R.color.normalColor));
            note.setTextColor(getResources().getColor(R.color.chooseColor));
        } else {//todolist
            hiddenDrawerLayout();
            menu.findItem(R.id.action_add).setVisible(false);
            menu.findItem(R.id.action_show_finish_gone).setVisible(sfinish);
            menu.findItem(R.id.action_show_finish).setVisible(!sfinish);

            noteLayout.setVisibility(View.GONE);
            todoLayout.setVisibility(View.VISIBLE);
            todo.setTextColor(getResources().getColor(R.color.chooseColor));
            note.setTextColor(getResources().getColor(R.color.normalColor));
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar_todo:
                isNote = false;
                invalidateOptionsMenu();//通知系统刷新Menu
                break;
            case R.id.toolbar_note:
                isNote = true;
                invalidateOptionsMenu();//通知系统刷新Menu
                break;
            case R.id.fab://悬浮按钮被点击
                if (isNote) {
                    Intent intent = new Intent(this, NoteActivity.class);
                    startActivity(intent);
                } else {
                    FragmentManager fm = getSupportFragmentManager();
                    InputBottom editNameDialog = new InputBottom();
                    editNameDialog.show(fm, "bottom_dialog");
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        switch (requestCode) {
            case NOTE_EDIT:
            case NOTE_ADD:
//                Toast.makeText(this, "进来", Toast.LENGTH_SHORT).show();
//                noteAdapteradapter.notifyDataSetChanged();
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    protected void onDestroy() {
        saveTodoList();
        NoteDB.getInstance().close();
        super.onDestroy();
    }

    /**
     * 隐藏滑动窗口
     */
    private void hiddenDrawerLayout(){
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(false);
            actionBar.setHomeAsUpIndicator(R.drawable.dir);
        }
    }

    /**
     * 显示滑动窗口
     */
    private void showDrawerLayout(){
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
//            actionBar.setHomeAsUpIndicator(R.drawable.dir);
        }
    }


    /**
     * 查找满足条件的todoList，更新数据
     *
     * @param searchTagName 搜索条件
     *                      ********************************注意：搜索功能不完善********************************
     */
    private void searchTags(String searchTagName) {
        if (todoList_save == null) {//搜索开始,需要把结果复制一份
            todoList_save = new LinkedList<>();
            todoList_save.addAll(todoList);
        } else {//复原操作
            todoList.clear();
            todoList.addAll(todoList_save);
            adapter.notifyDataSetChanged();
        }

        int size = todoList.size();
        for (int i = size - 1; i >= 0; i--) {
            if (!todoList.get(i).content.contains(searchTagName)) {
                todoList.remove(i);
                adapter.notifyItemRemoved(i);
            }
        }


    }
}
